#!/bin/bash

# Depends:
#     $WKSPACE
#     $SCRIPT_BASE
#     $USER
#     $SERVER_ADDR
#     $ERROR_LOG
source ${0%/*}/../config.local.sh

if [ $# != 2 ]; then
    echo MD.sh MD_PATH HTML_PATH.html
    exit
fi

if [ ! -f $1 ]; then
    echo Invalid input path: $1
    exit
fi

srcFile=`basename $1`
outputFile=`basename $2`
destDir=`dirname $2`
workspace=$WKSPACE/md
scriptDir=$SCRIPT_BASE/md/server

if [ ! -d $destDir ]; then
    echo Invalid output dir: $destDir
    exit
fi

scp $1 $USER@$SERVER_ADDR:$workspace
ssh $USER@$SERVER_ADDR "python $scriptDir/MD.py $workspace/$srcFile $workspace/$outputFile $workspace/$ERROR_LOG"
scp $USER@$SERVER_ADDR:$workspace/$outputFile* $destDir

if [ -f $2 ]; then
    echo Successfully generate HTML: $2
else
    echo Failed to generate HTML with error:
    ssh $USER@$SERVER_ADDR "cat $workspace/$ERROR_LOG"
fi

ssh $USER@$SERVER_ADDR "rm -rf $workspace/*"
